/*
*	@file
*	@author  Thomas Kroes <t.kroes at tudelft.nl>
*	@version 1.0
*	
*	@section LICENSE
*	
*	Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*	
*	Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*	Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*	Neither the name of the TU Delft nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
*	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#pragma once

#include "vtkAmbientOcclusionPass.h"
#include "vtkObjectFactory.h"
#include <assert.h>
#include "vtkRenderState.h"
#include "vtkRenderer.h"
#include "vtkgl.h"
#include "vtkFrameBufferObject.h"
#include "vtkTextureObject.h"
#include "vtkShaderProgram2.h"
#include "vtkShader2.h"
#include "vtkShader2Collection.h"
#include "vtkUniformVariables.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkTextureUnitManager.h"
#include "vtkImageAppendComponents.h"
#include "vtkImageCast.h"
#include "vtkImageShiftScale.h"
#include "vtkImageData.h"

// to be able to dump intermediate passes into png files for debugging.
// only for vtkAmbientOcclusionPass developers.
//#define VTK_GAUSSIAN_BLUR_PASS_DEBUG

#include "vtkPNGWriter.h"
#include "vtkImageImport.h"
#include "vtkPixelBufferObject.h"
#include "vtkPixelBufferObject.h"
#include "vtkImageExtractComponents.h"
#include "vtkCamera.h"
#include "vtkMath.h"

vtkStandardNewMacro(vtkAmbientOcclusionPass);

vtkAmbientOcclusionPass::vtkAmbientOcclusionPass()
{
	this->FrameBufferObject		= vtkFrameBufferObject::New();
	this->RenderPass			= vtkTextureObject::New();
	this->DepthPass				= vtkTextureObject::New();
	this->NormalPass			= vtkTextureObject::New();
	this->SSAOTexture			= vtkTextureObject::New();
	this->Preprocess			= vtkShaderProgram2::New();
	this->SSAO					= vtkShaderProgram2::New();
	this->SSAOFilterH			= vtkShaderProgram2::New();
	this->SSAOFilterV			= vtkShaderProgram2::New();
	this->RandomBuffer	= vtkTextureObject::New();
	this->WindowSize[0]			= -1;
	this->WindowSize[1]			= -1;
	this->Supported				= false;
	this->SupportChecked		= false;

	printf("Loading shaders\n");
	
	this->LoadPreprocessingShader();
	this->LoadSSAOShader();
}

vtkAmbientOcclusionPass::~vtkAmbientOcclusionPass()
{
}

void vtkAmbientOcclusionPass::PrintSelf(ostream& os, vtkIndent indent)
{
	this->Superclass::PrintSelf(os,indent);
}

void vtkAmbientOcclusionPass::PreRender(const vtkRenderState* RenderState)
{
	int CurrentWindowSize[2];
	RenderState->GetWindowSize(CurrentWindowSize);

	if (CurrentWindowSize[0] == this->WindowSize[0] && CurrentWindowSize[1] == this->WindowSize[1])
		return;

	printf("Render window size has changed (%d x %d), updating graphics resources\n", CurrentWindowSize[0], CurrentWindowSize[1]);

	vtkOpenGLRenderWindow* RenderWindow = (vtkOpenGLRenderWindow*)RenderState->GetRenderer()->GetRenderWindow();

	printf("Updating render pass texture object\n");
	this->RenderPass->SetContext(RenderWindow);
	this->RenderPass->Create2D(CurrentWindowSize[0], CurrentWindowSize[1], 4, VTK_UNSIGNED_CHAR, false);

	printf("Updating depth texture object\n");
	this->DepthPass->SetContext(RenderWindow);
	this->DepthPass->Create2D(CurrentWindowSize[0], CurrentWindowSize[1], 1, VTK_VOID, false);
	
	printf("Updating normal texture object\n");
	this->NormalPass->SetContext(RenderWindow);
	this->NormalPass->Create2D(CurrentWindowSize[0], CurrentWindowSize[1], 4, VTK_UNSIGNED_CHAR, false);

	printf("Updating SSAO texture object\n");
	this->SSAOTexture->SetContext(RenderWindow);
	this->SSAOTexture->Create2D(CurrentWindowSize[0], CurrentWindowSize[1], 4, VTK_UNSIGNED_CHAR, false);

	for (int i = 0; i < 2; i++)
		this->WindowSize[i] = CurrentWindowSize[i];
}

bool vtkAmbientOcclusionPass::IsSupported(const vtkRenderState* RenderState)
{
	if (this->GetDelegatePass() == NULL)
		return false;

	if (!this->SupportChecked)
	{
		vtkOpenGLRenderWindow* RenderWindow = (vtkOpenGLRenderWindow*)RenderState->GetRenderer()->GetRenderWindow();

		bool LocalSupported = vtkFrameBufferObject::IsSupported(RenderWindow);

		if (!LocalSupported)
			vtkErrorMacro("FBOs are not supported by the context. Cannot blur the image.");
		
		if (LocalSupported)
		{
			LocalSupported = vtkTextureObject::IsSupported(RenderWindow);

			if (!LocalSupported)
				vtkErrorMacro("Texture Objects are not supported by the context. Cannot blur the image.");
		}

		if (LocalSupported)
		{
			LocalSupported = vtkShaderProgram2::IsSupported(RenderWindow);

			if (!LocalSupported)
				vtkErrorMacro("GLSL is not supported by the context. Cannot blur the image.");
		}

		if (LocalSupported)
		{
			this->FrameBufferObject->SetContext(RenderWindow);
			
			this->FrameBufferObject->SetColorBuffer(0, this->RenderPass);
			this->FrameBufferObject->SetDepthBuffer(this->DepthPass);
			this->FrameBufferObject->SetNumberOfRenderTargets(1);
			this->FrameBufferObject->SetActiveBuffer(0);
			this->FrameBufferObject->SetDepthBufferNeeded(true);

			this->Preprocess->SetContext(static_cast<vtkOpenGLRenderWindow*>(this->FrameBufferObject->GetContext()));
			this->SSAO->SetContext(static_cast<vtkOpenGLRenderWindow*>(this->FrameBufferObject->GetContext()));

			GLint savedCurrentDrawBuffer;
			glGetIntegerv(GL_DRAW_BUFFER,&savedCurrentDrawBuffer);
			
			LocalSupported = this->FrameBufferObject->StartNonOrtho(this->WindowSize[0], this->WindowSize[1], false);
			
			if (!LocalSupported)
			{
				vtkErrorMacro("The requested FBO format is not supported by the context. Cannot blur the image.");
			}
			else
			{
				this->FrameBufferObject->UnBind();
				glDrawBuffer(static_cast<GLenum>(savedCurrentDrawBuffer));
			}
		}

		this->Supported			= LocalSupported;
		this->SupportChecked	= true;

		int RandomSize[2] = { 64, 64 };

		vtkSmartPointer<vtkImageNoiseSource>		ImageNoiseSources[3];
		vtkSmartPointer<vtkImageAppendComponents>	ImageAppendComponents = vtkImageAppendComponents::New();

		for (int i = 0; i < 3; i++)
		{
			ImageNoiseSources[i] = vtkImageNoiseSource::New();
			ImageNoiseSources[i]->SetMinimum(0.0);
			ImageNoiseSources[i]->SetMaximum(255.0);
			ImageNoiseSources[i]->SetWholeExtent(0, RandomSize[0], 0, RandomSize[1], 0, 0);

			vtkSmartPointer<vtkImageCast> ImageCast = vtkSmartPointer<vtkImageCast>::New();
			ImageCast->SetInputConnection(ImageNoiseSources[i]->GetOutputPort());
			ImageCast->SetOutputScalarTypeToUnsignedChar();
			ImageCast->Update();

			ImageAppendComponents->AddInputConnection(0, ImageCast->GetOutputPort());
		}

		ImageAppendComponents->Update();

		this->RandomBuffer->SetContext(RenderWindow);

		vtkSmartPointer<vtkPixelBufferObject> PBO = vtkPixelBufferObject::New();
		
		unsigned int Dimensions[2] = { RandomSize[0], RandomSize[1] };
		int Increments[2] = { 0, 0 };
		
		PBO->SetContext(RenderWindow);
		PBO->Upload2D(VTK_UNSIGNED_CHAR, ImageAppendComponents->GetOutput()->GetScalarPointer(), Dimensions, 3, Increments);

		this->RandomBuffer->Create2D(RandomSize[0], RandomSize[1], 3, PBO, false);
	}

	return this->Supported;
}

void vtkAmbientOcclusionPass::Render(const vtkRenderState* RenderState)
{
	this->PreRender(RenderState);
	
	if (!this->IsSupported(RenderState))
	{
		this->DelegatePass->Render(RenderState);
		this->NumberOfRenderedProps += this->DelegatePass->GetNumberOfRenderedProps();
		return;
	}

	this->FrameBufferObject->UnBind();
	
	this->RenderDelegate(RenderState, this->WindowSize[0], this->WindowSize[1], this->WindowSize[0], this->WindowSize[1], this->FrameBufferObject, this->RenderPass);
	// this->RenderDelegate(RenderState, this->WindowSize[0], this->WindowSize[1], this->WindowSize[0], this->WindowSize[1], this->FrameBufferObject, this->SSAOTexture);

	this->Preprocess->Use();
	this->RenderDelegate(RenderState, this->WindowSize[0], this->WindowSize[1], this->WindowSize[0], this->WindowSize[1], this->FrameBufferObject, this->NormalPass);
	this->Preprocess->Restore();

	this->SSAO->Build();

	this->FrameBufferObject->Start(this->WindowSize[0], this->WindowSize[1], false);
	
	this->SSAO->Use();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0);
	this->SSAOTexture->Bind();

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glBegin(GL_QUADS);
	glVertex2f(0.0f, 0.0f);
	glVertex2f(1.0f, 0.0f);
	glVertex2f(1.0f, 1.0f);
	glVertex2f(0.0f, 1.0f);
	glEnd();
	

// 	glBegin(GL_TRIANGLES);                      // Drawing Using Triangles
// 	glVertex3f( 0.0f, 1.0f, 0.0f);              // Top
// 	glVertex3f(-1.0f,-1.0f, 0.0f);              // Bottom Left
// 	glVertex3f( 1.0f,-1.0f, 0.0f);              // Bottom Right
// 	glEnd();
//
//	this->RenderDelegate(RenderState, this->WindowSize[0], this->WindowSize[1], this->WindowSize[0], this->WindowSize[1], this->FrameBufferObject, this->SSAOTexture);
	

	this->SSAOTexture->UnBind();
	this->SSAO->Restore();

	//

	/*
	this->NormalPass->CopyToFrameBuffer(0, 0, this->WindowSize[0] - 1, this->WindowSize[1] - 1, 0, 0, this->WindowSize[0], this->WindowSize[1]);

	GLint savedDrawBuffer;
	glGetIntegerv(GL_DRAW_BUFFER,&savedDrawBuffer);

	this->Preprocess->Build();	
	this->SSAO->Build();

	if(this->Preprocess->GetLastBuildStatus() != VTK_SHADER_PROGRAM2_LINK_SUCCEEDED)
		vtkErrorMacro("Couldn't build the shader program. At this point , it can be an error in a shader or a driver bug.");

	if(this->SSAO->GetLastBuildStatus() != VTK_SHADER_PROGRAM2_LINK_SUCCEEDED)
		vtkErrorMacro("Couldn't build the shader program. At this point , it can be an error in a shader or a driver bug.");

	GLint SavedCurrentDrawBuffer;
	glGetIntegerv(GL_DRAW_BUFFER, &SavedCurrentDrawBuffer);

	
	

	this->NormalPass->Bind();
	
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	

	this->FrameBufferObject->RenderQuad(0, this->WindowSize[0] - 1, 0, this->WindowSize[1] - 1);

	this->NormalPass->UnBind();

	

	this->FrameBufferObject->UnBind();

	glDrawBuffer(static_cast<GLenum>(savedDrawBuffer));

	this->Preprocess->Restore();
	

	this->NormalPass->Bind();

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	glDisable(GL_ALPHA_TEST);
	glDisable(GL_BLEND);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_LIGHTING);
	glDisable(GL_SCISSOR_TEST);

	
	
	this->NormalPass->UnBind();

	vtkgl::ActiveTexture(vtkgl::TEXTURE0);
	*/

	this->WriteRGBAucTextureToDisk(this->RenderPass, "render.png");
	this->WriteRGBAucTextureToDisk(this->NormalPass, "normal.png");
	this->WriteFloatTextureToDisk(this->DepthPass, "depth.png");
	this->WriteRGBAucTextureToDisk(this->SSAOTexture, "ssao.png");
	this->WriteRGBucTextureToDisk(this->RandomBuffer, "random.png");
}

void vtkAmbientOcclusionPass::ReleaseGraphicsResources(vtkWindow* Window)
{
}

void vtkAmbientOcclusionPass::WriteRGBucTextureToDisk(vtkTextureObject* TextureObject, const char* Name)
{
	const int NoComponents = 3;

	vtkSmartPointer<vtkPixelBufferObject> PixelBufferObject = TextureObject->Download();

	const int NoElements = TextureObject->GetWidth() * TextureObject->GetHeight();

	unsigned char* RawColorData = new unsigned char[NoComponents * NoElements];

	unsigned int Dimensions[2] = { TextureObject->GetWidth(), TextureObject->GetHeight() };
	vtkIdType Increments[2] = { 0, 0 };

	const bool Status = PixelBufferObject->Download2D(VTK_UNSIGNED_CHAR, RawColorData, Dimensions, NoComponents, Increments);

	assert("check" && Status);

	vtkSmartPointer<vtkImageImport> Importer = vtkImageImport::New();
	Importer->CopyImportVoidPointer(RawColorData, NoComponents * NoElements * sizeof(unsigned char));
	Importer->SetDataScalarTypeToUnsignedChar();
	Importer->SetNumberOfScalarComponents(NoComponents);
	Importer->SetWholeExtent(0, TextureObject->GetWidth() - 1, 0, TextureObject->GetHeight() - 1, 0, 0);
	Importer->SetDataExtentToWholeExtent();

	delete[] RawColorData;

	vtkSmartPointer<vtkImageExtractComponents> ImageExtractComponents = vtkImageExtractComponents::New();
	ImageExtractComponents->SetInputConnection(Importer->GetOutputPort());
	ImageExtractComponents->SetComponents(0, 1, 2);

	vtkSmartPointer<vtkPNGWriter> PNGWriter = vtkPNGWriter::New();
	PNGWriter->SetFileName(Name);
	PNGWriter->SetInputConnection(ImageExtractComponents->GetOutputPort());
	PNGWriter->Write();
}

void vtkAmbientOcclusionPass::WriteRGBAucTextureToDisk(vtkTextureObject* TextureObject, const char* Name)
{
	const int NoComponents = 4;

	vtkSmartPointer<vtkPixelBufferObject> PixelBufferObject = TextureObject->Download();

	const int NoElements = TextureObject->GetWidth() * TextureObject->GetHeight();

	unsigned char* RawColorData = new unsigned char[NoComponents * NoElements];
	
	unsigned int Dimensions[2] = { TextureObject->GetWidth(), TextureObject->GetHeight() };
	vtkIdType Increments[2] = { 0, 0 };

	const bool Status = PixelBufferObject->Download2D(VTK_UNSIGNED_CHAR, RawColorData, Dimensions, NoComponents, Increments);

	assert("check" && Status);

	vtkSmartPointer<vtkImageImport> Importer = vtkImageImport::New();
	Importer->CopyImportVoidPointer(RawColorData, NoComponents * NoElements * sizeof(unsigned char));
	Importer->SetDataScalarTypeToUnsignedChar();
	Importer->SetNumberOfScalarComponents(NoComponents);
	Importer->SetWholeExtent(0, TextureObject->GetWidth() - 1, 0, TextureObject->GetHeight() - 1, 0, 0);
	Importer->SetDataExtentToWholeExtent();
	
	delete[] RawColorData;

	vtkSmartPointer<vtkImageExtractComponents> ImageExtractComponents = vtkImageExtractComponents::New();
	ImageExtractComponents->SetInputConnection(Importer->GetOutputPort());
	ImageExtractComponents->SetComponents(0, 1, 2);

	vtkSmartPointer<vtkPNGWriter> PNGWriter = vtkPNGWriter::New();
	PNGWriter->SetFileName(Name);
	PNGWriter->SetInputConnection(ImageExtractComponents->GetOutputPort());
	PNGWriter->Write();
}

void vtkAmbientOcclusionPass::WriteFloatTextureToDisk(vtkTextureObject* TextureObject, const char* Name)
{
	vtkSmartPointer<vtkPixelBufferObject> PixelBufferObject = TextureObject->Download();

	const int NoElements = TextureObject->GetWidth() * TextureObject->GetHeight();

	float* RawDepthData = new float[NoElements];

	unsigned int Dimensions[2] = { TextureObject->GetWidth(), TextureObject->GetHeight() };
	vtkIdType Increments[2] = { 0, 0 };
	
	const bool Status = PixelBufferObject->Download2D(VTK_FLOAT, RawDepthData, Dimensions, 1, Increments);
	
	assert("check" && Status);

	vtkSmartPointer<vtkImageImport> ImageImporter = vtkImageImport::New();
	ImageImporter->CopyImportVoidPointer(RawDepthData, NoElements * sizeof(float));
	ImageImporter->SetDataScalarTypeToFloat();
	ImageImporter->SetNumberOfScalarComponents(1);
	ImageImporter->SetWholeExtent(0, TextureObject->GetWidth() - 1, 0, TextureObject->GetHeight() - 1, 0, 0);
	ImageImporter->SetDataExtentToWholeExtent();
	
	delete[] RawDepthData;
	
	vtkSmartPointer<vtkImageShiftScale> ImageShiftScale = vtkSmartPointer<vtkImageShiftScale>::New();
	ImageShiftScale->SetScale(255.0);
	ImageShiftScale->SetInputConnection(ImageImporter->GetOutputPort());

	vtkSmartPointer<vtkImageCast> ImageCast = vtkSmartPointer<vtkImageCast>::New();
	ImageCast->SetOutputScalarTypeToUnsignedChar();
	ImageCast->SetInputConnection(ImageShiftScale->GetOutputPort());
	
	vtkSmartPointer<vtkImageAppendComponents> AppendFilter = vtkSmartPointer<vtkImageAppendComponents>::New();
	AppendFilter->SetInputConnection(0, ImageCast->GetOutputPort());
	AppendFilter->AddInputConnection(0, ImageCast->GetOutputPort());
	AppendFilter->AddInputConnection(0, ImageCast->GetOutputPort());
	
	AppendFilter->Update();

	vtkSmartPointer<vtkPNGWriter> PNGWriter = vtkPNGWriter::New();
	PNGWriter->SetFileName(Name);
	PNGWriter->SetInputConnection(AppendFilter->GetOutputPort());
	PNGWriter->Write();
}

void vtkAmbientOcclusionPass::LoadPreprocessingShader()
{
	printf("Loading pre-processing shader\n");

	// Create vertex and fragment shaders
	vtkShader2* PreprocessVS = vtkShader2::New();
	vtkShader2* PreprocessFS = vtkShader2::New();

	PreprocessVS->SetType(VTK_SHADER_TYPE_VERTEX);
	PreprocessFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	// Load vertex shader from disk
	std::ifstream VS("C://Workspaces//vtkaopass//build//Debug//preprocess.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	PreprocessVS->SetSourceCode(StrVS.c_str());

	// Load fragment shader from disk
	std::ifstream FS("C://Workspaces//vtkaopass//build//Debug//preprocess.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	PreprocessFS->SetSourceCode(StrFS.c_str());

	PreprocessVS->SetContext(this->Preprocess->GetContext());
	PreprocessFS->SetContext(this->Preprocess->GetContext());

	this->Preprocess->GetShaders()->AddItem(PreprocessFS);
	this->Preprocess->GetShaders()->AddItem(PreprocessVS);

	PreprocessVS->Delete();
	PreprocessFS->Delete();
}

void vtkAmbientOcclusionPass::LoadSSAOShader()
{
	printf("Loading SSAO shader\n");

	// Create vertex and fragment shaders
	vtkShader2* SSAOVS = vtkShader2::New();
	vtkShader2* SSAOFS = vtkShader2::New();

	SSAOVS->SetType(VTK_SHADER_TYPE_VERTEX);
	SSAOFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	// Load vertex shader from disk
	std::ifstream VS("C:\\Workspaces\\vtkaopass\\build\\Debug\\ssao.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	SSAOVS->SetSourceCode(StrVS.c_str());

	// Load fragment shader from disk
	std::ifstream FS("C:\\Workspaces\\vtkaopass\\build\\Debug\\ssao.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	SSAOFS->SetSourceCode(StrFS.c_str());

	SSAOVS->SetContext(this->SSAO->GetContext());
	SSAOFS->SetContext(this->SSAO->GetContext());

	this->SSAO->GetShaders()->AddItem(SSAOVS);
	this->SSAO->GetShaders()->AddItem(SSAOFS);

	SSAOVS->Delete();
	SSAOFS->Delete();
}



/*
#include "vtkAmbientOcclusionPass.h"

#include "vtkObjectFactory.h"
#include <assert.h>
#include "vtkRenderState.h"
#include "vtkRenderer.h"
#include "vtkgl.h"
#include "vtkFrameBufferObject.h"
#include "vtkTextureObject.h"
#include "vtkShaderProgram2.h"
#include "vtkShader2.h"
#include "vtkShader2Collection.h"
#include "vtkUniformVariables.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkTextureUnitManager.h"

// to be able to dump intermediate passes into png files for debugging.
// only for vtkAmbientOcclusionPass developers.
//#define VTK_GAUSSIAN_BLUR_PASS_DEBUG

#include "vtkPNGWriter.h"
#include "vtkImageImport.h"
#include "vtkPixelBufferObject.h"
#include "vtkPixelBufferObject.h"
#include "vtkImageExtractComponents.h"
#include "vtkCamera.h"
#include "vtkMath.h"

class vec3
{
public:
	union{
		struct{float x, y, z;};
		struct{float s, t, p;};
		struct{float r, g, b;};
	};
	vec3() : x(0.0f), y(0.0f), z(0.0f){}
	~vec3(){}
	vec3(float num) : x(num), y(num), z(num){}
	vec3(float x, float y, float z) : x(x), y(y), z(z){}

	vec3(vec3 &u) : x(u.x), y(u.y), z(u.z){}
	vec3& operator = (vec3 &u){x = u.x; y = u.y; z = u.z; return *this;}
	vec3 operator - (){return vec3(-x, -y, -z);}
	float* operator & (){return (float*)this;}
	vec3& operator += (float num){x += num; y += num; z += num; return *this;}
	vec3& operator += (vec3 &u){x += u.x; y += u.y; z += u.z; return *this;}
	vec3& operator -= (float num){x -= num; y -= num; z -= num; return *this;}
	vec3& operator -= (vec3 &u){x -= u.x; y -= u.y; z -= u.z; return *this;}
	vec3& operator *= (float num){x *= num; y *= num; z *= num; return *this;}
	vec3& operator *= (vec3 &u){x *= u.x; y *= u.y; z *= u.z; return *this;}
	vec3& operator /= (float num){x /= num; y /= num; z /= num; return *this;}
	vec3& operator /= (vec3 &u){x /= u.x; y /= u.y; z /= u.z; return *this;}
	friend vec3 operator + (vec3 &u, float num){return vec3(u.x + num, u.y + num, u.z + num);}
	friend vec3 operator + (float num, vec3 &u){return vec3(num + u.x, num + u.y, num + u.z);}
	friend vec3 operator + (vec3 &u, vec3 &v){return vec3(u.x + v.x, u.y + v.y, u.z + v.z);}
	friend vec3 operator - (vec3 &u, float num){return vec3(u.x - num, u.y - num, u.z + num);}
	friend vec3 operator - (float num, vec3 &u){return vec3(num - u.x, num - u.y, num - u.z);}
	friend vec3 operator - (vec3 &u, vec3 &v){return vec3(u.x - v.x, u.y - v.y, u.z - v.z);}
	friend vec3 operator * (vec3 &u, float num){return vec3(u.x * num, u.y * num, u.z * num);}
	friend vec3 operator * (float num, vec3 &u){return vec3(num * u.x, num * u.y, num * u.z);}
	friend vec3 operator * (vec3 &u, vec3 &v){return vec3(u.x * v.x, u.y * v.y, u.z * v.z);}
	friend vec3 operator / (vec3 &u, float num){return vec3(u.x / num, u.y / num, u.z / num);}
	friend vec3 operator / (float num, vec3 &u){return vec3(num / u.x, num / u.y, num / u.z);}
	friend vec3 operator / (vec3 &u, vec3 &v){return vec3(u.x / v.x, u.y / v.y, u.z / v.z);}
};

vtkStandardNewMacro(vtkAmbientOcclusionPass);

extern const char *vtkAmbientOcclusionPassShader_fs;

void vtkAmbientOcclusionPass::LoadPreprocessShaderProgram()
{
	this->Preprocess->SetContext(static_cast<vtkOpenGLRenderWindow*>(this->FrameBufferObject->GetContext()));

	// Create vertex and fragment shaders
	vtkShader2* PreprocessVS = vtkShader2::New();
	vtkShader2* PreprocessFS = vtkShader2::New();

	PreprocessVS->SetType(VTK_SHADER_TYPE_VERTEX);
	PreprocessFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	// Load vertex shader from disk
	std::ifstream VS("C://Workspaces//vtkaopass//build//Debug//preprocess.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	PreprocessVS->SetSourceCode(StrVS.c_str());

	// Load fragment shader from disk
	std::ifstream FS("C://Workspaces//vtkaopass//build//Debug//preprocess.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	PreprocessFS->SetSourceCode(StrFS.c_str());

	PreprocessVS->SetContext(this->Preprocess->GetContext());
	PreprocessFS->SetContext(this->Preprocess->GetContext());

	this->Preprocess->GetShaders()->AddItem(PreprocessFS);
	this->Preprocess->GetShaders()->AddItem(PreprocessVS);
	
	// Build the shader program
	this->Preprocess->Build();	

	PreprocessVS->Delete();
	PreprocessFS->Delete();
}

void vtkAmbientOcclusionPass::LoadSSAOShaderProgram()
{
	this->SSAO->SetContext(static_cast<vtkOpenGLRenderWindow*>(this->FrameBufferObject->GetContext()));

	// Create vertex and fragment shaders
	vtkShader2* SSAOVS = vtkShader2::New();
	vtkShader2* SSAOFS = vtkShader2::New();

	SSAOVS->SetType(VTK_SHADER_TYPE_VERTEX);
	SSAOFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	// Load vertex shader from disk
	std::ifstream VS("C:\\Workspaces\\vtkaopass\\build\\Debug\\ssao.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	SSAOVS->SetSourceCode(StrVS.c_str());

	// Load fragment shader from disk
	std::ifstream FS("C:\\Workspaces\\vtkaopass\\build\\Debug\\ssao.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	SSAOFS->SetSourceCode(StrFS.c_str());

	SSAOVS->SetContext(this->SSAO->GetContext());
	SSAOFS->SetContext(this->SSAO->GetContext());

	//this->SSAO->GetShaders()->AddItem(SSAOVS);
	this->SSAO->GetShaders()->AddItem(SSAOFS);
	
	SSAOVS->Delete();
	SSAOFS->Delete();

	// Build the shader program
	this->SSAO->Build();
}

void vtkAmbientOcclusionPass::LoadSSAOFilterHShaderProgram()
{
	this->SSAOFilterH->SetContext(static_cast<vtkOpenGLRenderWindow*>(this->FrameBufferObject->GetContext()));

	// Create vertex and fragment shaders
	vtkShader2* SSAOFilterHVS = vtkShader2::New();
	vtkShader2* SSAOFilterHFS = vtkShader2::New();

	SSAOFilterHVS->SetType(VTK_SHADER_TYPE_VERTEX);
	SSAOFilterHFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	// Load vertex shader from disk
	std::ifstream VS("C:\\Workspaces\\vtkaopass\\build\\Debug\\ssaofilter.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	SSAOFilterHVS->SetSourceCode(StrVS.c_str());

	// Load fragment shader from disk
	std::ifstream FS("C:\\Workspaces\\vtkaopass\\build\\Debug\\ssaofilterh.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	SSAOFilterHFS->SetSourceCode(StrFS.c_str());

	SSAOFilterHVS->SetContext(this->SSAOFilterH->GetContext());
	SSAOFilterHFS->SetContext(this->SSAOFilterH->GetContext());

	this->SSAOFilterH->GetShaders()->AddItem(SSAOFilterHFS);
	this->SSAOFilterH->GetShaders()->AddItem(SSAOFilterHVS);

	SSAOFilterHVS->Delete();
	SSAOFilterHFS->Delete();

	// Build the shader program
	this->SSAOFilterH->Build();
}

void vtkAmbientOcclusionPass::LoadSSAOFilterVShaderProgram()
{
	this->SSAOFilterV->SetContext(static_cast<vtkOpenGLRenderWindow*>(this->FrameBufferObject->GetContext()));

	// Create vertex and fragment shaders
	vtkShader2* SSAOFilterVVS = vtkShader2::New();
	vtkShader2* SSAOFilterVFS = vtkShader2::New();

	SSAOFilterVVS->SetType(VTK_SHADER_TYPE_VERTEX);
	SSAOFilterVFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	// Load vertex shader from disk
	std::ifstream VS("C:\\Workspaces\\vtkaopass\\build\\Debug\\ssaofilter.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	SSAOFilterVVS->SetSourceCode(StrVS.c_str());

	// Load fragment shader from disk
	std::ifstream FS("C:\\Workspaces\\vtkaopass\\build\\Debug\\ssaofilterv.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	SSAOFilterVFS->SetSourceCode(StrFS.c_str());

	SSAOFilterVVS->SetContext(this->SSAOFilterV->GetContext());
	SSAOFilterVFS->SetContext(this->SSAOFilterV->GetContext());

	this->SSAOFilterV->GetShaders()->AddItem(SSAOFilterVFS);
	this->SSAOFilterV->GetShaders()->AddItem(SSAOFilterVVS);

	SSAOFilterVVS->Delete();
	SSAOFilterVFS->Delete();

	// Build the shader program
	this->SSAOFilterV->Build();
}

void vtkAmbientOcclusionPass::CreateRandomTexture()
{
// 	srand(GetTickCount());
// 
// 	glGenTextures(1, &RandomUnitVectorsTexture);
// 
// 	vec3* RandomUnitVectorsTextureData = new vec3[64 * 64];
// 
// 	for(int i = 0; i < 64 * 64; i++)
// 	{
// 		RandomUnitVectorsTextureData[i].x = (float)rand() / (float)RAND_MAX * 2.0f - 1.0f;
// 		RandomUnitVectorsTextureData[i].y = (float)rand() / (float)RAND_MAX * 2.0f - 1.0f;
// 		RandomUnitVectorsTextureData[i].z = (float)rand() / (float)RAND_MAX * 2.0f - 1.0f;
// 
// 		RandomUnitVectorsTextureData[i] = normalize(RandomUnitVectorsTextureData[i]);
// 
// 		RandomUnitVectorsTextureData[i] = RandomUnitVectorsTextureData[i] * 0.5f + 0.5f;
// 	}
// 
// 	glBindTexture(GL_TEXTURE_2D, RandomUnitVectorsTexture);
// 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// 	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 64, 64, 0, GL_RGB, GL_FLOAT, RandomUnitVectorsTextureData);
// 
// 	delete [] RandomUnitVectorsTextureData;
}

// ----------------------------------------------------------------------------
vtkAmbientOcclusionPass::vtkAmbientOcclusionPass()
{
	this->Initialized				= false;
	this->FrameBufferObject			= vtkFrameBufferObject::New();
	this->RenderPass						= vtkTextureObject::New();
	this->Result					= vtkTextureObject::New();
	this->Supported					= false;
	this->SupportProbed				= false;
	this->Preprocess				= vtkShaderProgram2::New();
	this->SSAO						= vtkShaderProgram2::New();
	this->SSAOFilterH				= vtkShaderProgram2::New();
	this->SSAOFilterV				= vtkShaderProgram2::New();
	this->SSAOUniformVariables		= vtkUniformVariables::New();
	this->FBO						= -1;
	this->RandomUnitVectorsTexture	= -1;
	this->NormalBuffer				= -1;
	this->DepthBuffer				= -1;
	this->SSAOTexture				= -1;
	this->BlurTexture				= -1;
}

// ----------------------------------------------------------------------------
vtkAmbientOcclusionPass::~vtkAmbientOcclusionPass()
{
}

void vtkAmbientOcclusionPass::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

void vtkAmbientOcclusionPass::Init()
{
	if (this->Initialized)
		return;

	this->LoadPreprocessShaderProgram();
	this->LoadSSAOShaderProgram();
	this->LoadSSAOFilterHShaderProgram();
	this->LoadSSAOFilterVShaderProgram();

	//this->RenderDelegate(s, width, height, width, height, this->FrameBufferObject, this->Pass1);

	const bool Preprocess	= this->Preprocess->GetLastBuildStatus() == VTK_SHADER_PROGRAM2_LINK_SUCCEEDED;
	const bool SSAO			= this->SSAO->GetLastBuildStatus() == VTK_SHADER_PROGRAM2_LINK_SUCCEEDED;
	const bool SSAOFilterH	= this->SSAOFilterH->GetLastBuildStatus() == VTK_SHADER_PROGRAM2_LINK_SUCCEEDED;
	const bool SSAOFilterV	= this->SSAOFilterV->GetLastBuildStatus() == VTK_SHADER_PROGRAM2_LINK_SUCCEEDED;

	if (!Preprocess || !SSAO || !SSAOFilterH || !SSAOFilterV)
	{
		vtkErrorMacro("Couldn't build one of the shader programs. At this point, it can be an error in a shader or a driver bug.");
		return;
	}

	if (!this->Preprocess->IsValid())
		vtkErrorMacro(<<this->Preprocess->GetLastValidateLog());

	if (!this->SSAO->IsValid())
		vtkErrorMacro(<<this->SSAO->GetLastValidateLog());

	if (!this->SSAOFilterH->IsValid())
		vtkErrorMacro(<<this->SSAOFilterH->GetLastValidateLog());

	if (!this->SSAOFilterV->IsValid())
		vtkErrorMacro(<<this->SSAOFilterV->GetLastValidateLog());
	
	int DepthBuffer					= 0;
	int NormalBuffer				= 0;
	int RandomUnitVectorsTexture	= 0;
	float Color[4] = { 0.3f, 0.3f, 1.0f, 1.0f };

	this->SSAOUniformVariables->SetUniformi("DepthBuffer", 1, &DepthBuffer);
	this->SSAOUniformVariables->SetUniformi("NormalBuffer", 1, &NormalBuffer);
	this->SSAOUniformVariables->SetUniformi("RandomUnitVectorsTexture", 1, &RandomUnitVectorsTexture);
	this->SSAOUniformVariables->SetUniformfv("Color", 1, 4, Color);
	this->SSAO->SetUniformVariables(this->SSAOUniformVariables);

//	glGenFramebuffers(1, &this->FBO);

// 	glGenTextures(1, &this->NormalBuffer);
// 	glGenTextures(1, &this->DepthBuffer);
// 	glGenTextures(1, &this->SSAOTexture);
// 	glGenTextures(1, &this->BlurTexture);

	this->Initialized = true;
}

void vtkAmbientOcclusionPass::Render(const vtkRenderState* RenderState)
{
	if (this->DelegatePass == NULL)
		return;
	
	//this->DelegatePass->Render(RenderState);

	vtkRenderer* Renderer = RenderState->GetRenderer();
	vtkOpenGLRenderWindow* RenderWindow=vtkOpenGLRenderWindow::SafeDownCast(Renderer->GetRenderWindow());
	
	vtkTextureUnitManager* TextureUnitManager = RenderWindow->GetTextureUnitManager();

	int w;
	int h;
	int size[2];
	RenderState->GetWindowSize(size);
	w=size[0];
	h=size[1];

	this->FrameBufferObject->SetContext(Renderer->GetRenderWindow());
	
	

	this->RenderPass->SetContext(Renderer->GetRenderWindow());

	if (!this->Initialized)
		this->RenderPass->Create2D(w, h, 4, VTK_UNSIGNED_CHAR, false);
	
	this->Init();

	this->FrameBufferObject->SetColorBuffer(0, this->RenderPass);
	this->FrameBufferObject->SetNumberOfRenderTargets(1);
	this->FrameBufferObject->SetActiveBuffer(0);
	this->FrameBufferObject->SetDepthBufferNeeded(true);
	//this->FrameBufferObject->Start(w, h, false);
	
	this->FrameBufferObject->UnBind();

	
	GLint savedCurrentDrawBuffer;
	glGetIntegerv(GL_DRAW_BUFFER, &savedCurrentDrawBuffer);
	bool Supported = this->FrameBufferObject->StartNonOrtho(w, h, false);

	if (!Supported)
	{
		vtkErrorMacro("The requested FBO format is not supported by the context. Cannot blur the image.");
	}
	else
	{
		this->FrameBufferObject->UnBind();
		glDrawBuffer(static_cast<GLenum>(savedCurrentDrawBuffer));
	}

	GLint savedDrawBuffer;
	glGetIntegerv(GL_DRAW_BUFFER, &savedDrawBuffer);

	this->RenderDelegate(RenderState, w, h, w, h, this->FrameBufferObject, this->RenderPass);
	
	this->RenderPass->Bind();

	int sourceId = TextureUnitManager->Allocate();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0 + static_cast<GLenum>(sourceId));
	this->RenderPass->Bind();
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	this->SSAOUniformVariables->SetUniformi("source", 1, &sourceId);

	// this->SSAO->Use();

	this->RenderPass->CopyToFrameBuffer(0, 0, 0, 0, 0, 0, w, h);
	
	this->RenderPass->UnBind();
	
	// vtkgl::ActiveTexture(vtkgl::TEXTURE0);

	//this->SSAO->Use();

	//this->FrameBufferObject->RenderQuad(0,w-1,0,h-1);
	/*
	this->Pass1->Bind();

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// Prepare blitting
	glDisable(GL_ALPHA_TEST);
	glDisable(GL_BLEND);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_LIGHTING);
	glDisable(GL_SCISSOR_TEST);

	this->Pass1->CopyToFrameBuffer(0, 0, 0, 0, 0, 0, w, h);
	
	this->FrameBufferObject->RenderQuad(0,w-1,0,h-1);

	this->Pass1->UnBind();

	vtkgl::ActiveTexture(vtkgl::TEXTURE0);


	{
		// Save first pass in file for debugging.
		vtkPixelBufferObject *pbo=this->RenderPass->Download();

		unsigned char *openglRawData=new unsigned char[4*w*h];
		unsigned int dims[2];
		dims[0]=w;
		dims[1]=h;
		vtkIdType incs[2];
		incs[0]=0;
		incs[1]=0;
		bool status=pbo->Download2D(VTK_UNSIGNED_CHAR,openglRawData,dims,4,incs);
		assert("check" && status);
		pbo->Delete();

		// no pbo
		this->RenderPass->Bind();
		glGetTexImage(GL_TEXTURE_2D,0,GL_RGBA,GL_UNSIGNED_BYTE,openglRawData);
		this->RenderPass->UnBind();

		vtkImageImport *importer=vtkImageImport::New();
		importer->CopyImportVoidPointer(openglRawData,4*w*h*sizeof(unsigned char));
		importer->SetDataScalarTypeToUnsignedChar();
		importer->SetNumberOfScalarComponents(4);
		importer->SetWholeExtent(0,w-1,0,h-1,0,0);
		importer->SetDataExtentToWholeExtent();
		delete[] openglRawData;

		vtkImageExtractComponents *rgbaToRgb=vtkImageExtractComponents::New();
		rgbaToRgb->SetInputConnection(importer->GetOutputPort());
		rgbaToRgb->SetComponents(0,1,2);

		vtkPNGWriter *writer=vtkPNGWriter::New();
		writer->SetFileName("BlurPass1.png");
		writer->SetInputConnection(rgbaToRgb->GetOutputPort());
		importer->Delete();
		rgbaToRgb->Delete();
		writer->Write();
		writer->Delete();
	}
}

void vtkAmbientOcclusionPass::ReleaseGraphicsResources(vtkWindow *w)
{
	this->Superclass::ReleaseGraphicsResources(w);
}
*/